package com.amat0urheu.controller.studentController;

import com.amat0urheu.annotation.OperateLog;
import com.amat0urheu.pojo.OperationLog;
import com.amat0urheu.pojo.ReturnRes;
import com.amat0urheu.service.LogService;
import com.amat0urheu.service.impl.LoginServiceImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


@RestController
@RequestMapping("/api")
@Slf4j
public class LoginController {



    final LoginServiceImpl loginService;

    @Autowired
    public LoginController(LoginServiceImpl loginService) {
        this.loginService = loginService;
    }
    @Autowired
    LogService logService;
    @PostMapping("/login")
    public ReturnRes login(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String captchaId,
                           @RequestParam String captcha
                          ) {
        if (loginService.validateCaptcha(username, captcha, captchaId)) {

            String token = loginService.login(username, password);
            System.out.println("token=="+token);
            if (token != null) {

                OperationLog operationLog = new OperationLog();
                operationLog.setOperateTime(new Date());
                operationLog.setUsername(username);
                operationLog.setAction("登录成功");
                operationLog.setParams("username:"+username+" password:*****");
                logService.inserSysLog(operationLog);
                return new ReturnRes(true, token, "登录成功");
            } else {
                OperationLog operationLog = new OperationLog();
                operationLog.setUsername(username);
                operationLog.setOperateTime(new Date());
                operationLog.setAction("登录失败,输入密码错误");
                operationLog.setParams("usernamme:"+username+" password:"+password);
                logService.inserSysLog(operationLog);
                return new ReturnRes(false, "用户名或密码错误");
            }
        }
        return new ReturnRes(false, "验证码输入错误");


    }
}
